<?php

function logActions()
{
	error_reporting(E_ALL);
	if(DEBUG_LVL == 1)
	{
		ini_set('display_errors', 'On');
	}
	else if (DEBUG_LVL == 0)
	{
		ini_set('display_errors', 'Off');
		ini_set('log_errors', 'On');
		ini_set('error_log', ROOT . DS . 'tmp' . DS . 'logs' . DS . 'error.log');
		
	}
}

function redirectURL()
{
	global $url;
	$urlArray = explode('/', $url);
	array_shift($urlArray);
	$controller = array_shift($urlArray);
	$action = array_shift($urlArray);
	$parameters = $urlArray;
	
	$controllerClassName = ucfirst(strtolower($controller)) . 'Controller';
	$modelClassName = ucfirst(strtolower(rtrim($controller, 's')));
	$actionName = $action;
	
	$controllerClass = new $controllerClassName(strtolower($controller), $modelClassName, $actionName);
	
	if(method_exists($controllerClass, $actionName))
	{
		call_user_func(array($controllerClass,'beforeFilter'));
		call_user_func_array(array($controllerClass,$actionName), $parameters);
	}
	else
	{
		echo 'the function does not exist';
	}
	
	
}

function __autoload($className)
{
	$controllerClass = ROOT . DS . 'app' . DS . 'controllers' . DS . strtolower($className) . '.php';
	$modelClass = ROOT . DS . 'app' . DS . 'models' . DS . strtolower($className) . '.php';
	$dbClass = ROOT . DS . 'lib' . DS . 'db' . DS . $className . '.php';
	$templatePath = ROOT . DS . 'app' . DS . 'views' . DS . 'template.php';
	
	if(file_exists($controllerClass))
	{
		require_once($controllerClass);
	}
	elseif(file_exists($modelClass))
	{
		require_once($modelClass);
	}
	elseif(file_exists($dbClass))
	{
		require_once($dbClass);
	}
	elseif(file_exists($templatePath))
	{
		require_once($templatePath);
	}
	
}

logActions();
redirectURL();